﻿@page "/"
@using qYun.Shared.Models

@inject IHttpClientFactory HttpClient
@implements IDisposable

@* <div>最后更新时间：@DateTime.Now.ToString("HH:mm:ss.fff")</div> *@

<ul>
    <li>@_gasModel.CurrentStatus</li>
    <li>@_gasModel.AtmosphericPressure</li>
</ul>

@code{
    private GasModel _gasModel=new GasModel();
    private readonly CancellationTokenSource _cts = new();
    private Timer _timer;
    //private GasRecord _gasRecord=new(1,1,0);

    protected override async Task OnInitializedAsync()
    {
        //初始化数据
        await FetchDataTaskAsync();
        //await StartTimerAsync();
        await Task.Delay(10000);
        _timer = new Timer(async _ =>
        {
            await InvokeAsync(async () =>
            {
                await FetchDataTaskAsync();
               
            });
        }, null, 0, 10000);
        
    }
    //
    private async Task StartTimerAsync()
    {
        try
        {
            using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
            while (await timer.WaitForNextTickAsync(_cts.Token))
            {
                await InvokeAsync(async () =>
                {
                    try
                    {
                        await FetchDataTaskAsync();
                        //StateHasChanged();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"更新失败: {ex.Message}");
                    }
                });
                //StateHasChanged();
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("定时器已正常停止");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"定时器异常: {ex.Message}");
        }
    }
    //

    //
    private async Task FetchDataTaskAsync()
    {
        try
        {
            using var client = HttpClient.CreateClient();
            var response = await client.GetAsync("http://localhost:5491/api/Demo/update");
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<GasModel>();
                if (result != null)
                    _gasModel = new GasModel()
                    {
                        CurrentStatus = result.CurrentStatus, 
                        AtmosphericPressure = result.AtmosphericPressure
                    };
                //StateHasChanged();
                Console.WriteLine($"数据更新成功：{_gasModel.AtmosphericPressure}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"请求异常: {ex.Message}");
        }
    }
    public void Dispose()
    {
        _cts.Cancel();
        GC.SuppressFinalize(this);
    }

    public record GasRecord(
        int Id,
        int CurrentStatus,
        float AtmosphericPressure
        );

}